package com.wei.shopping.controller;

import com.wei.shopping.entrty.PageResult;
import com.wei.shopping.entrty.QueryPageBean;
import com.wei.shopping.entrty.Result;
import com.wei.shopping.pojo.Login;
import com.wei.shopping.pojo.Notices;
import com.wei.shopping.pojo.UserInfo;
import com.wei.shopping.pojo.UserRole;
import com.wei.shopping.service.UserService;
import com.wei.shopping.utils.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RequestMapping("/user")
@RestController
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Value("${qiniuyun}")
    private String qiniuyun;

    /**
     * 普通用户注册
     * @param map
     * @return
     */
    @RequestMapping("/regist")
    public Result userRegist(@RequestBody Map map){
        //获取手机号和验证码
        String mobilephone = (String)map.get("mobilephone");
        String code = (String)map.get("code");
        String username = (String)map.get("username");
        String password = (String)map.get("password");
        String email = (String)map.get("email");
        String sex = (String)map.get("sex");
        String school = (String)map.get("school");
        //拼接成redis中的key
        String newmobilephone = "+86"+mobilephone+SMSUtils.LOGIN_CHECK;
        //从redis中获取验证码，判断是否相同
        String realcode = stringRedisTemplate.opsForValue().get(newmobilephone);
        System.out.println("realcode："+realcode);
        System.out.println("mobilephone: " + mobilephone);
        //判断验证码是否正确
        if(realcode != null && mobilephone != null && code.equals(realcode)){
        /*if(true){*/
            //判断用户名和手机号是否是否已经存在，若存在则提示，重复
            UserInfo user = userService.findByPhoneAndUsername(username, mobilephone);
            System.out.println("user: " + user);
            if(user == null){
                //不存在，则进行插入注册
                try{
                    UserInfo userInfo = new UserInfo();
                    Login login = new Login();
                    //先插入login表
                    //盐加密,把密码进行md5加密
                    String passwords = new Md5Hash(password, "Campus-shops").toString();
                    String userid = KeyUtil.genUniqueKey();
                    //设置login信息
                    login.setId(KeyUtil.genUniqueKey());login.setUserid(userid);login.setUsername(username);login.setPassword(passwords);
                    //向登陆表中添加数据
                    userService.addLogin(login);
                    //设置用户详情数据
                    userInfo.setUserid(userid);userInfo.setUsername(username);userInfo.setPassword(passwords);userInfo.setMobilephone(mobilephone);userInfo.setEmail(email);
                    //这是初始头像
                    userInfo.setUimage("http://qsazz6un4.hd-bkt.clouddn.com/94cd81e1-fe35-451a-877f-3469996463c1.jpg");
                    userInfo.setSex(sex);
                    userInfo.setSchool(school);
                    //注册用户详情信息
                    userService.regist(userInfo);
                    //向权限角色表中添加数据
                    UserRole userRole = new UserRole();
                    userRole.setUserid(userid);userRole.setRoleid(1);userRole.setIdentity("普通用户");
                    //添加权限数据
                    userService.addRole(userRole);
                }catch(Exception e){
                    //插入失败
                    return new Result(false,"注册失败，请重试");
                }
            }else{
                //存在
                return new Result(false,"该用户名和手机号已经注册");
            }
        }else{
            //验证码不正确
            return new Result(false,"验证码错误");
        }
        return new Result(true,"注册成功");
    }
    //普通用户登陆
    @RequestMapping("/login")
    public Result login(@RequestBody Map map, HttpServletRequest request){
        //获取用户名和密码和验证码
        String username = (String) map.get("username");
        String password = (String) map.get("password");

        String code = (String) map.get("code");
        System.out.println(code);
        String realcode = ValidateCode.getCode();
        System.out.println("realcode:" + realcode);
        //判断验证码是否正确
        if(realcode != null && code != null && realcode.equalsIgnoreCase(code)){
            //验证码争取，判断用户名和密码
            //把密码进行加密
            String passwords = new Md5Hash(password, "Campus-shops").toString();
            UserInfo user = userService.login(username,passwords);
            if(user != null){
                //登陆成功
                //设置session，保存登陆状态
                HttpSession session = request.getSession();
                session.setAttribute("username",username);
                session.setAttribute("userid",user.getUserid());
                session.setAttribute("school",user.getSchool());
                return new Result(true,"登陆成功");
            }else{
                //登陆失败,用户名和密码错误
                return new Result(false,"用户名或密码错误");
            }
        }else{
            //验证码不正确
            return new Result(false,"验证码错误,请重新输入");
        }
    }

    /**
     *图片验证码
     * */
    @RequestMapping(value = "/images", method = {RequestMethod.GET, RequestMethod.POST})
    public void images(HttpServletResponse response) throws IOException {
        response.setContentType("image/jpeg");
        //禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        ValidateCode vCode = new ValidateCode(820, 200, 5, 80);
        vCode.write(response.getOutputStream());
    }

    /**
     * 获取手机验证码
     */
    @RequestMapping("/getcode")
    public Result getcode(@RequestParam("mobilephone") String phone){
        Integer realcode = ValidateCodeUtils.generateValidateCode(6);
        String newphone = "+86"+phone;
        try{
            SMSUtils.sendShortMessage(SMSUtils.LOGIN_CHECK,new String[]{newphone},new String[]{realcode.toString()});
        }catch(Exception e){
            return new Result(false,"信息发送失败，请重试");
        }
        //把验证码保存到redis中，时长为5分钟
        stringRedisTemplate.opsForValue().set(newphone+SMSUtils.LOGIN_CHECK, String.valueOf(realcode),300, TimeUnit.SECONDS);
        return new Result(true,"信息发送成功,请注意查收");
    }

    /**
     * 查找全部的普通用户
     */
    @RequestMapping("/findall")
    public PageResult findUserAll(@RequestParam("userstatus") Integer userstatus, @RequestBody QueryPageBean queryPageBean){
        try{
            PageResult findall = userService.findall(userstatus,queryPageBean);
            return findall;
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 封禁用户
     * @param userid
     * @return
     */
    @RequestMapping("/userban")
    public Result userban(String userid){
        System.out.println("userid："+userid);
        try{
            userService.userBan(userid);
            return new Result(true,"封禁成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"请求失败");
        }
    }

    /**
     * 解封用户
     * @param userid
     * @return
     */
    @RequestMapping("/relieve")
    public Result relieve(String userid){
        System.out.println("relieve："+userid);
        try{
            userService.relieve(userid);
            return new Result(true,"解封成功");
        }catch(Exception e){
            e.printStackTrace();
            return new Result(false,"解封异常");
        }
    }
    /**
     * 设置管理员
     * 管理员后台，设置普通用户权限
     */
    @RequestMapping("/setadmin")
    public Result setadmin(String userid){
        try{
            userService.setadmin(userid);
            return new Result(true,"设置为管理员成功");
        }catch(Exception e){
            e.printStackTrace();
            return new Result(false,"设为管理员失败");
        }
    }
    @RequestMapping("/findNowUser")
    public Result findNowUser(HttpSession session){
        try{
            String userid = (String)session.getAttribute("userid");
            UserInfo user = userService.findById(userid);
            return new Result(true,"查询用户成功",user);
        }catch(Exception e){
            e.printStackTrace();
            return new Result(false,"插叙当前用户信息失败");
        }
    }

    /**
     * 修改用户数据
     * @param userInfo
     * @return
     */
    @RequestMapping("/editmessage")
    public Result editmessage(@RequestBody UserInfo userInfo){
        try{
            userService.editmessage(userInfo);
            return new Result(true,"修改信息成功");
        }catch(Exception e){
            e.printStackTrace();
            return new Result(false,"修改信息失败");
        }
    }
    //上传头像
    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile")MultipartFile imgFile){
        //获取文件的原始文件明
        String originalFilename = imgFile.getOriginalFilename();
        //获取文件的后缀名
        int last = originalFilename.lastIndexOf(".");
        String substring = originalFilename.substring(last);
        //获取随机的文件名称
        String filename = UUID.randomUUID().toString()+ substring;
        //上传文件到服务器
        try{
            QiniuUtils.upload2Qinui(imgFile.getBytes(), filename);
            Result result = new Result(true,"图片上传成功");
            result.setData(qiniuyun + filename);
            System.out.println(qiniuyun + filename);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, "图片上传失败");
        }
    }

    /**
     * 修改密码
     * @param map
     * @param session
     * @return
     */
    @RequestMapping("/changepass")
    public Result changepass(@RequestBody Map map,HttpSession session){
        //获取登陆的userid
        String userid = (String)session.getAttribute("userid");
        //判断旧密码是否正确
        try{
            Result changepass = userService.changepass(map, userid);
            return changepass;
        }catch(Exception e){
            return new Result(false,"修改密码失败");
        }
    }

    /**
     * 获取通知信息
     * @param session
     * @return
     */
    @GetMapping("/notice")
    public Result getNotice(HttpSession session){
        //获取登录的userid
        String userid = (String) session.getAttribute("userid");
        //通过用户id查找通知消息
        try{
            List<Notices> notice = userService.getNotice(userid);
            return new Result(true,"获取通知信息成功",notice);
        }catch(Exception e){
            return new Result(false,"获取通知信息异常");
        }
    }

    /**
     * 退出登陆
     * @param session
     * @return
     */
    @RequestMapping("/quit")
    public Result quit(HttpSession session){
        session.removeAttribute("username");
        session.removeAttribute("userid");
        return new Result(true,"退出成功");
    }

    /**
     * 获取用户登陆信息
     * @param session
     * @return
     */
    @RequestMapping("/getusermess")
    public Result getusermess(HttpSession session){
        String userid =(String) session.getAttribute("userid");
        if(userid ==null){
            return new Result(false,"失败");
        }
        UserInfo byId = userService.findById(userid);
        return new Result(true,"查找成功",byId);
    }
}
